<?php

declare (strict_types = 1);

namespace app\service\develop;

use app\model\develop\DistrictModel;
use own\helps\ImportExcelTool;
use think\facade\Db;

class DistrictService
{
    /**
     * 搜索条件
     * @param array $param
     */
    private function _searchMap(array $param): array
    {
        $map = [];
        //上级ID
        if($id = $param['id'] ?? '') {
            $map[] = ['id', '=', $id];
        }
        //状态：0禁用 1启用
        $status = $param['status'] ?? '';
        if(is_numeric($status)) {
            $map[] = ['status', '=', $status];
        }
        //上级ID
        $parentId = $param['parent_id'] ?? '';
        if(is_numeric($parentId)) {
            $map[] = ['parent_id', '=', $parentId];
        }
        //地名
        if($name = $param['name'] ?? '') {
            $map[] = ['name', 'like', '%'.trim($name).'%'];
        }
        //省份
        if($province = $param['province'] ?? '') {
            $map[] = ['province', 'like', '%'.trim($province).'%'];
        }
        //城市
        if($city = $param['city'] ?? '') {
            $map[] = ['city', 'like', '%'.trim($city).'%'];
        }
        //区/县
        if($district = $param['district'] ?? '') {
            $map[] = ['district', 'like', '%'.trim($district).'%'];
        }
        //乡/镇
        if($town = $param['town'] ?? '') {
            $map[] = ['town', 'like', '%'.trim($town).'%'];
        }
        //简称
        if($shortname = $param['shortname'] ?? '') {
            $map[] = ['shortname', 'like', '%'.trim($shortname).'%'];
        }
        //区域选项
        if($townId = $param['town_id'] ?? 0) {
            $map[] = ['id', '=', $townId];
        } else if($districtId = $param['district_id'] ?? 0) {
            if(DistrictModel::where('parent_id', $districtId)->find()) {
                $map[] = ['parent_id', '=', $districtId];
            } else {
                $map[] = ['id', '=', $districtId];
            }
        } else if($cityId = $param['city_id'] ?? 0) {
            $map[] = ['parent_id', '=', $cityId];
        } else if($provinceId = $param['province_id'] ?? 0) {
            $map[] = ['parent_id', '=', $provinceId];
        }
        return $map;
    }
    /**
     * 地区列表
     * @param array $param
     */
    public function list(array $param): array
    {
        $map = $this->_searchMap($param);
        $list = DistrictModel::where($map)
            ->order('id asc')
            ->pages($param)
            ->select();
        return list_fmt($list, DistrictModel::where($map)->count());
    }
    /**
     * 地区编辑
     * @param array $data
     * @param integer $id
     */
    public function edit(array $data, int $id): void
    {
        $parent = $data['parent_id'] ? DistrictModel::find($data['parent_id']) : '';
        $addId = 0;
        if($id) {
            $address = DistrictModel::find($id);
            if(!$address) {
                tips('未找到地区信息，修改失败');
            }
        } else {
            $address = new DistrictModel();
            $addId = DistrictModel::max('id');
            $address->id = $addId < 1000000 ? 1000000 : $addId + 1;
            $address->parent_id = $data['parent_id'];
            //路径、层级深度
            $address->path = $address->path . '/' . $id;
            $address->depth = count(explode('/', $address->path));
        }
        $address->name = trim($data['name']);
        $this->_nameRepeat($address->name, $address->parent_id, $id);
        $address->english = $data['english'];
        //行政区域
        if($parent) {
            $address->province = $parent->province;
            $address->city = $parent->city ?: $data['city'];
            $address->district = $parent->district ?: $data['district'];
            $address->town = $parent->town ?: $data['town'];
        } else {
            $address->province = trim($data['province']);
            $address->city = $data['city'];
            $address->district = $data['district'];
            $address->town = $data['town'];
        }
        $address->pinyin = $data['pinyin'];
        $address->jianpin = $data['jianpin'];
        $address->firstchar = $data['firstchar'];
        $address->lng = $data['lng'];
        $address->lat = $data['lat'];
        $address->fullname = $data['fullname'];
        if(!$address->save()) {
            tips('保存地区信息失败');
        }
    }
    /**
     * 地区查重
     * @param string $name 地名
     * @param integer $parent_id 父级ID
     * @param integer $id 地区ID
     */
    private function _nameRepeat(string $name, int $parent_id, int $id)
    {
        $where = DistrictModel::where('name', $name)
            ->where('parent_id', $parent_id);
        if($id) {
            $where->where('id', '<>', $id);
        }
        if($where->find()) {
            tips('已有相同的地名，请重新填写');
        }
    }
    /**
     * 地区状态修改
     * @param integer $id 地区id
     */
    public function status(int $id): int
    {
        $address = DistrictModel::find($id);
        if(!$address) {
            tips('未找到地区信息，修改失败');
        }
        $address->status = $address->status ? 0 : 1;
        if(!$address->save()) {
            tips('修改失败');
        }
        return $address->status;
    }
    /**
     * 地区详情
     * @param integer $id
     */
    public function info(int $id)
    {
        return DistrictModel::find($id);
    }
    /**
     * 地区导入
     */
    public function import($file)
    {
        $data = make(ImportExcelTool::class)->getData($file);
        unset($data[0]); //删除头信息
        $this->addressImport($data);
    }
    /**
     * 导入地区信息
     * @param array $data 地区信息
     */
    public static function addressImport(array $data): void
    {
        $list = array_chunk($data, 5000);
        foreach($list as $arr) {
            $addAddress = [];
            foreach($arr as $key => $address) {
                $addAddress[] = [
                    'id' => $address[0],
                    'parent_id' => $address[1],
                    'name' => $address[2],
                    'english' => $address[3]?:'',
                    'province' => $address[4],
                    'city' => $address[5]?:'',
                    'district' => $address[6]?:'',
                    'town' => $address[7]?:'',
                    'shortname' => $address[8]?:'',
                    'pinyin' => $address[9]?:'',
                    'jianpin' => $address[10]?:'',
                    'firstchar' => $address[11],
                    'lng' => $address[12],
                    'lat' => $address[13],
                    'depth' => $address[14],
                    'fullname' => $address[15]?:'',
                    'path' => $address[16],
                    'status' => 1,
                ];
                if($key % 10 == 0) {
                    Db::table('configure_address')->insertAll($addAddress);
                    $addAddress = [];
                }
            }
            if($addAddress) {
                Db::table('configure_address')->insertAll($addAddress);
            }
        }
    }
    /**
     * 地区选项
     * @param integer $parent_id
     */
    public function option(int $parent_id)
    {
        return DistrictModel::field('id,name,lng,lat,firstchar')
            ->where('parent_id', $parent_id)
            ->where('status', 1)
            ->order('firstchar asc')->order('id asc')
            ->select();
    }
}